/*
qnettest - Qt4 application for testing network performance
Copyright (C) 2007  Pyry Haulos

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include <QtCore>
#include <QtNetwork>
#include "tcpclienthelper.hpp"
#include "tcpclient.hpp"
#include "tcpproto.hpp"

TcpClientHelper::TcpClientHelper(TcpClientArgs * args, TcpProtoTestData * data, QObject * parent):QThread(parent)
{
	this->args = args;
	testdata = data;
	packet_count = 0;
}

TcpClientHelper::~TcpClientHelper()
{
	// cleanup ?
}

void TcpClientHelper::run()
{
	socket = new QTcpSocket;
	socket->connectToHost(args->address, args->port);

	if (!socket->waitForConnected()) {
		showError(socket->errorString());
		return;
	}
#ifdef TCPCLIENTHELPER_DEBUG
	qDebug() << "TcpClientHelper::run():" << QObject::tr("connected");
#endif

	testproto = new TcpProto(socket, testdata);

	QTime time;
	time.start();

	QTime interval;
	interval.start();

	forever {
		if (interval.elapsed() > args->interval * packet_count) {
			if (testproto->send(args->send_bytes, args->recv_bytes))
				packet_count++;
			else
				break;
		}

		if (socket->error() >= 0) {
			packet_count = -1;
			break;
		}

		if (socket->state() != QTcpSocket::ConnectedState) {
			packet_count = -1;
			break;
		}

		if (time.elapsed() > args->time)
			break;
	}

	socket->abort();
	socket->disconnectFromHost();

#ifdef TCPCLIENTHELPER_DEBUG
	qint32 actual_up_KBps = (qint32) (((float) packet_count * (float) (args->send_bytes)) / (float) args->time);
	qint32 actual_down_KBps = (qint32) (((float) packet_count * (float) (args->recv_bytes)) / (float) args->time);

	qDebug() << "TcpClientHelper::run():" << QObject::tr("sent %1 packets, upstream was %2 KB/s, downstream %3 KB/s").arg(packet_count).arg(actual_up_KBps).arg(actual_down_KBps);
#endif

	emit report(packet_count);

	delete socket;
	delete testproto;
}

void TcpClientHelper::showError(QString error)
{
	qWarning() << "TcpClientHelper::error():" << error;
}
